import { useState } from "react";
import { ShareCard } from "./ShareCard";
import s from "./styles.module.scss";
import { style } from "../data/data";
import { Box, Modal } from "@mui/material";
import { Loader } from "./UI/loader";
import { NewsInfo } from "./NewsInfo";
import { getSumm } from "../helpers/functions";

export const Shares = ({ positions }) => {
  const [data, setData] = useState(null);
  const [open, setOpen] = useState(false);

  const handleOpen = async (func) => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
    setData(null);
  };

  return (
    <div className={s.shares}>
      <div className={s.shares__title}>Список активов</div>

      {positions.map((elem, key) => (
        <>
          {getSumm(elem.quantityLots.units, elem.currentPrice.units) > 0 ? (
            <ShareCard
              elem={elem}
              key={key}
              s={s}
              setData={setData}
              onOpenModal={handleOpen}
            />
          ) : null}
        </>
      ))}

      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        sx={{ overflow: "hidden" }}
      >
        <Box
          sx={{ ...style, width: "1000px", height: "500px", textAlign: "left" }}
        >
          {data ? (
            <>
              {data.totalResults == 0 ? (
                <div>Новостей нет</div>
              ) : (
                data.articles.map((elem, key) => (
                  <NewsInfo news={elem} key={key} s={s} />
                ))
              )}
            </>
          ) : (
            <div style={{ textAlign: "center" }}>
              <div>Загрузка новостей</div>
              <Loader width={"50px"} height={"50px"} />
            </div>
          )}
        </Box>
      </Modal>
    </div>
  );
};
